#!/usr/bin/env bash

# 打包后的服务名字
# 测试
ServerName="tanbao2"

GOPATH="/Users/cc/go"

echo "the package you build is $ServerName"
if [ ! -d "$GOPATH/src/$ServerName" ]; then
        echo "$ServerName does not exist "
        exit
fi


cd $GOPATH/src/$ServerName

# 打包的压缩包名
PackageName=${ServerName}_pkg

#包存放的远程服务器路径
PackageSaveHostPath=/userdata1/tanbao2/pkg-sources

# 正式或者开发环境
ENV="dev"

# 根据环境设置Host
if [[ ${ENV} == "dev" ]]; then
    HOST=tb3_test
else
    HOST=""
fi

# 移除包名，App，和压缩包
rm -rf ${ServerName}
rm -rf ${PackageName}
rm ${PackageName}.tar.gz

echo "start to build package..."

GOOS=linux GOARCH=amd64 go build -o  ./${ServerName} main.go

if [ -f ./${ServerName} ]; then
    echo "build success."
else
    echo "build failed."
    exit
fi

echo "start to pack..."
#mkdir -p ${PackageName}/${ConfigPath}
mkdir -p ${PackageName}

cp ./${ServerName}  ${PackageName}/
cp -r ./config ${PackageName}/

rm ${PackageName}/*.go
cp ./*.sh ${PackageName}/

tar  -czvf  ${PackageName}.tar.gz ${PackageName}

if [ -f ${PackageName}.tar.gz ]; then
     echo "pack finished..."
     echo "scp package to ${HOST} ..."
     scp ${PackageName}.tar.gz ${HOST}:${PackageSaveHostPath}
     echo "scp success..."
     # 移除包名，App，和压缩包
     rm -f ${PackageName}.tar.gz
     rm -rf ${ServerName}
     rm -rf ${PackageName}
     cd -
     pwd
     ssh ${HOST} 'bash -s' < ./server_deploy.sh ${ServerName} ${PackageSaveHostPath} ${PackageName}
     sleep 2

     echo -e '\r\n'
else
    echo "Pack failed..."
    exit
fi

